const db = require('../../mysql/index')
const time = require('../../utils/time')

exports.getvideos = async (req, res) => {
    db.query('SELECT * from bilibili_videos', async (err, results) => {
        if (err) return res.send({
            status: 1,
            message: err
        })
        let promiseList = []
        for (let i = 0; i < results.length; i++) {
            promiseList.push(new Promise((resolve, rejecte) => {
                db.query('SELECT username from bilibili_personal where account=?', [results[i].up], async (err, myres) => {
                    results[i].username = await myres[0].username
                    resolve()
                })
            }))
        }
        await Promise.allSettled(promiseList)
        res.send({
            status: 0,
            message: results.reverse()
        })
    })
}
exports.getvideosdetail = (req, res) => {
    db.query('SELECT * from bilibili_videos where id=?', [req.query.id], (err, restult) => {
        if (err) return res.send({
            status: 1,
            message: err.message
        })
        if (restult.length === 0) return res.send({
            status: 1,
            message: '视频丢失啦'
        })
        if (restult[0].coin != null) {
            let newArr = JSON.parse(restult[0].coin)
            const values = Object.values(newArr)
            const sum = values.reduce((accumulator, value) => {
                return parseInt(accumulator) + parseInt(value)
            }, 0);
            restult[0].coin = sum
        }
        db.query('SELECT username,profile,fans from bilibili_personal where account=?', [restult[0].up], (err, myres) => {
            if (err) return res.send({
                status: 1,
                message: err.message
            })
            restult[0].username = myres[0].username
            restult[0].profile = myres[0].profile
            if (myres[0].fans) {
                restult[0].fans = myres[0].fans.split(',').length
            } else {
                restult[0].fans = 0
            }
            db.query('SELECT id from bilibili_videos where up=?', [restult[0].up], (err, upres) => {
                restult[0].videoCount = upres.length
                db.query('SELECT id from bilibili_comment where video=?', [req.query.id], (err, commentres) => {
                    restult[0].commentCount = commentres.length
                    res.send({
                        status: 0,
                        message: restult
                    })
                })

            })

        })

    })
}

exports.isLook = (req, res) => {
    const myId = String(req.user.id)
    const state = {
        isGood: false,
        isDisgood: false,
        isCoin: false,
        isStar: false,
        isFan: false
    }
    db.query(`SELECT * from bilibili_videos where id = ?`, [req.query.id], (err, restult) => {
        if (err) return res.send({
            status: 0,
            message: err
        })
        const coin = JSON.parse(restult[0].coin)
        if (coin && coin[myId]) state.isCoin = true
        if (restult[0].good != null) {
            let resArr = restult[0].good.split(',')
            resArr.indexOf(String(myId)) != -1 && (state.isGood = true)
        }
        if (restult[0].star != null) {
            let resArr = restult[0].star.split(',')
            resArr.indexOf(String(myId)) != -1 && (state.isStar = true)
        }
        if (restult[0].disgood != null) {
            let resArr = restult[0].disgood.split(',')
            resArr.indexOf(String(myId)) != -1 && (state.isDisgood = true)
        }
        db.query(`SELECT idol from bilibili_personal where id = ?`, [req.user.id], (err, myres) => {
            db.query(`SELECT id from bilibili_personal where account = ?`, [restult[0].up], (err, idres) => {
                if (myres[0].idol != null) {
                    let idolArr = myres[0].idol.split(',')
                    if (idolArr.indexOf(String(idres[0].id)) != -1) state.isFan = true
                }
                res.send({
                    state: 0,
                    message: state
                })
            })
        })
    })
}


exports.good = (req, res) => {
    const { id } = req.body
    db.query(`SELECT good,disgood,up from bilibili_videos where id = ?`, [id], (err, restult) => {
        if (err) return res.send({
            status: 1,
            message: err
        })
        if (restult.length === 0) return res.send('参数错误')
        if (restult[0].disgood != null) {
            let disgoodArr = restult[0].disgood.split(',')
            let new_id = req.user.id.toString()
            if (disgoodArr.indexOf(new_id) != -1) {
                disgoodArr.splice(disgoodArr.indexOf(new_id), 1)
                restult[0].disgood = disgoodArr.toString()
                restult[0].disgood === '' && (restult[0].disgood = null)
            }
        }
        if (restult[0].good === null) return db.query('UPDATE bilibili_videos SET good=?,disgood=? where id=?', [req.user.id, restult[0].disgood, id], (err, myres) => {
            if (err) return res.send({
                status: 1,
                message: err
            })
            if (myres.affectedRows === 1) {
                db.query('SELECT good,good_who from bilibili_personal where account = ?', [restult[0].up], (err, up_res) => {
                    db.query('UPDATE bilibili_personal SET good=? where account=?', [up_res[0].good + 1, restult[0].up], (err, new_up_res) => {
                        if (err) return res.send({
                            status: 1,
                            message: err
                        })
                        db.query(`SELECT good_who from bilibili_personal where account = ?`, [req.user.username], (err, my_good_res) => {
                            let new_good
                            if (my_good_res[0].good_who) {
                                new_good = my_good_res[0].good_who.split(',')
                                new_good.push(id)
                                new_good = new_good.toString()
                            } else {
                                new_good = id
                            }
                            db.query('UPDATE bilibili_personal SET good_who=? where account=?', [new_good, req.user.username], (err, good_res) => {
                                if (good_res.affectedRows === 1) return res.send({
                                    status: 0,
                                    state: true,
                                    message: '点赞成功'
                                })
                            })
                        })
                    })
                })
            }
        })
        let resArr = restult[0].good.split(',')
        let strId = String(req.user.id)
        if (resArr.indexOf(strId) == -1) {
            restult[0].good += `,${req.user.id}`
            db.query('UPDATE bilibili_videos SET good=?,disgood=? where id=?', [restult[0].good, restult[0].disgood, id], (err, myres) => {
                if (err) return res.send({
                    status: 1,
                    message: err
                })
                if (myres.affectedRows === 1) {
                    db.query('SELECT good from bilibili_personal where account = ?', [restult[0].up], (err, up_res) => {
                        db.query('UPDATE bilibili_personal SET good=? where account=?', [up_res[0].good + 1, restult[0].up], (err, new_up_res) => {
                            if (err) return res.send({
                                status: 1,
                                message: err
                            })
                            if (new_up_res.affectedRows === 1) {
                                db.query(`SELECT good_who from bilibili_personal where account = ?`, [req.user.username], (err, my_good_res) => {
                                    let new_good
                                    if (my_good_res[0].good_who) {
                                        new_good = my_good_res[0].good_who.split(',')
                                        new_good.push(id)
                                        new_good = new_good.toString()
                                    } else {
                                        new_good = id
                                    }
                                    db.query('UPDATE bilibili_personal SET good_who=? where account=?', [new_good, req.user.username], (err, good_res) => {
                                        if (good_res.affectedRows === 1) return res.send({
                                            status: 0,
                                            state: true,
                                            message: '点赞成功'
                                        })
                                    })
                                })
                            }
                        })
                    })
                }

            })
        } else {
            resArr.splice(resArr.indexOf(strId), 1)
            let new_res_arr = resArr.toString()
            new_res_arr === '' && (new_res_arr = null)
            db.query('UPDATE bilibili_videos SET good=? where id=?', [new_res_arr, id], (err, myres) => {
                if (err) return res.send({
                    status: 1,
                    message: err
                })
                if (myres.affectedRows === 1) if (myres.affectedRows === 1) {
                    db.query('SELECT good from bilibili_personal where account = ?', [restult[0].up], (err, up_res) => {
                        db.query('UPDATE bilibili_personal SET good=? where account=?', [up_res[0].good - 1, restult[0].up], (err, new_up_res) => {
                            if (err) return res.send({
                                status: 1,
                                message: err
                            })
                            if (new_up_res.affectedRows === 1) {
                                db.query(`SELECT good_who from bilibili_personal where account = ?`, [req.user.username], (err, my_good_res) => {
                                    let new_good
                                    if (my_good_res[0].good_who) {
                                        new_good = my_good_res[0].good_who.split(',')
                                        new_good.splice(new_good.indexOf(id), 1)
                                        new_good.length === 0 ? new_good = null : new_good = new_good.toString()

                                    } else {
                                        new_good = my_good_res[0].good_who
                                    }
                                    db.query('UPDATE bilibili_personal SET good_who=? where account=?', [new_good, req.user.username], (err, good_res) => {
                                        if (good_res.affectedRows === 1) return res.send({
                                            status: 0,
                                            state: false,
                                            message: '取消点赞成功'
                                        })
                                    })
                                })
                            }
                        })
                    })
                }
            })
        }
    })

}

exports.disgood = (req, res) => {
    const { id } = req.body
    db.query(`SELECT good,disgood from bilibili_videos where id = ?`, [id], (err, restult) => {
        if (err) return res.send({
            status: 1,
            message: err
        })
        if (restult[0].good != null) {
            let goodArr = restult[0].good.split(',')
            let new_id = req.user.id.toString()
            if (goodArr.indexOf(new_id) != -1) {
                goodArr.splice(goodArr.indexOf(new_id), 1)
                restult[0].good = goodArr.toString()
                restult[0].good === '' && (restult[0].good = null)
            }
        }
        if (restult[0].disgood === null) return db.query('UPDATE bilibili_videos SET good=?,disgood=? where id=?', [restult[0].good, req.user.id, id], (err, myres) => {
            if (err) return res.send({
                status: 1,
                message: err
            })
            if (myres.affectedRows === 1) return res.send({
                status: 0,
                state: true,
                message: '收到反馈啦'
            })
        })
        let resArr = restult[0].disgood.split(',')
        let strId = String(req.user.id)
        if (resArr.indexOf(strId) == -1) {
            restult[0].disgood += `,${req.user.id}`
            db.query('UPDATE bilibili_videos SET good=?,disgood=? where id=?', [restult[0].good, restult[0].disgood, id], (err, myres) => {
                if (err) return res.send({
                    status: 1,
                    message: err
                })
                if (myres.affectedRows === 1) return res.send({
                    status: 0,
                    state: true,
                    message: '收到反馈啦'
                })
            })
        } else {
            resArr.splice(resArr.indexOf(strId), 1)
            let new_res_arr = resArr.toString()
            new_res_arr === '' && (new_res_arr = null)
            db.query('UPDATE bilibili_videos SET disgood=? where id=?', [new_res_arr, id], (err, myres) => {
                if (err) return res.send({
                    status: 1,
                    message: err
                })
                if (myres.affectedRows === 1) return res.send({
                    status: 0,
                    state: false,
                    message: '取消点赞成功'
                })
            })
        }
    })

}


exports.star = (req, res) => {
    const { id } = req.body
    db.query(`SELECT star,up from bilibili_videos where id = ?`, [id], (err, restult) => {
        if (err) return res.send({
            status: 1,
            message: err
        })
        if (restult[0].star === null) return db.query('UPDATE bilibili_videos SET star=? where id=?', [req.user.id, id], (err, myres) => {
            if (err) return res.send({
                status: 1,
                message: err
            })
            if (myres.affectedRows === 1) {
                db.query(`SELECT star from bilibili_personal where account = ?`, [req.user.username], (err, my_start_res) => {
                    let new_star
                    if (my_start_res[0].star) {
                        new_star = my_start_res[0].star.split(',')
                        new_star.push(id)
                        new_star = new_star.toString()
                    } else {
                        new_star = id
                    }
                    db.query('UPDATE bilibili_personal SET star=? where account=?', [new_star, req.user.username], (err, start_res) => {
                        if (myres.affectedRows === 1) return res.send({
                            status: 0,
                            state: true,
                            message: '收藏成功啦'
                        })
                    })
                })
            }
        })
        let resArr = restult[0].star.split(',')
        let strId = String(req.user.id)
        if (resArr.indexOf(strId) == -1) {
            restult[0].star += `,${req.user.id}`
            db.query('UPDATE bilibili_videos SET star=? where id=?', [restult[0].star, id], (err, myres) => {
                if (err) return res.send({
                    status: 1,
                    message: err
                })
                if (myres.affectedRows === 1) {
                    db.query(`SELECT star from bilibili_personal where account = ?`, [req.user.username], (err, my_start_res) => {
                        let new_star
                        if (my_start_res[0].star) {
                            new_star = my_start_res[0].star.split(',')
                            new_star.push(id)
                            new_star = new_star.toString()
                        } else {
                            new_star = id
                        }
                        db.query('UPDATE bilibili_personal SET star=? where account=?', [new_star, req.user.username], (err, start_res) => {
                            if (myres.affectedRows === 1) return res.send({
                                status: 0,
                                state: true,
                                message: '收藏成功啦'
                            })
                        })
                    })
                }
            })
        } else {
            resArr.splice(resArr.indexOf(strId), 1)
            let new_res_arr = resArr.toString()
            new_res_arr === '' && (new_res_arr = null)
            db.query('UPDATE bilibili_videos SET star=? where id=?', [new_res_arr, id], (err, myres) => {
                if (err) return res.send({
                    status: 1,
                    message: err
                })
                if (myres.affectedRows === 1) {
                    db.query(`SELECT star from bilibili_personal where account = ?`, [req.user.username], (err, my_start_res) => {
                        let new_star
                        if (my_start_res[0].star) {
                            new_star = my_start_res[0].star.split(',')
                            new_star.splice(new_star.indexOf(id), 1)
                            new_star.length === 0 ? new_star = null : new_star = new_star.toString()

                        } else {
                            new_star = my_start_res[0].star
                        }
                        db.query('UPDATE bilibili_personal SET star=? where account=?', [new_star, req.user.username], (err, start_res) => {
                            if (myres.affectedRows === 1) return res.send({
                                status: 0,
                                state: false,
                                message: '取消收藏成功啦'
                            })
                        })
                    })
                }
            })
        }
    })

}


exports.coin = (req, res) => {
    const { coinCount, id } = req.body
    if (coinCount != 1 && coinCount != 2) return res.send({
        status: 1,
        message: '检测到作弊'
    })
    db.query('SELECT coin,coin_who from bilibili_personal where id=?', [req.user.id], (err, restult) => {
        if (err) return res.send({
            status: 1,
            message: err
        })
        let coin = restult[0].coin
        if (coin < coinCount) return res.send({
            status: 1,
            message: '对不起,您的硬币不够了'
        })
        let coin_who
        restult[0].coin_who === null ? coin_who = null : coin_who = JSON.parse(restult[0].coin_who)
        const coin_reduce = (add_coin = 0) => {
            db.query('SELECT coin,up from bilibili_videos where id=?', [id], async (err, myres) => {
                if (err) return res.send({
                    status: 1,
                    message: err
                })
                if (myres[0].up === req.user.username) {
                    return res.send({
                        status: 1,
                        message: '您不能给自己投币'
                    })
                }
                let video_coin
                if (myres[0].coin != null) {
                    video_coin = JSON.parse(myres[0].coin)
                    video_coin[req.user.id] = parseInt(coinCount) + parseInt(video_coin[req.user.id])
                    video_coin = JSON.stringify(video_coin)
                } else {
                    video_coin = {
                        [req.user.id]: coinCount
                    }
                    video_coin = JSON.stringify(video_coin)
                }
                db.query('UPDATE bilibili_videos SET coin=? where id=?', [video_coin, id], (err, myres) => {
                    if (err) return res.send({
                        status: 1,
                        message: err
                    })
                    let newCoin = parseInt(restult[0].coin) - parseInt(coinCount)
                    db.query('UPDATE bilibili_personal SET coin=?,coin_who=? where id=?', [newCoin, coin_who, req.user.id], (err, myres) => {
                        if (err) return res.send({
                            status: 1,
                            message: err
                        })
                        if (myres.affectedRows === 1) res.send({
                            status: 0,
                            message: '投币成功'
                        })
                    })
                })
            })
        }
        try {
            if (!coin_who[id]) {
                coin_who[id] = 0
            }
            if (parseInt(coin_who[id]) + parseInt(coinCount) > 2) return res.send({
                status: 1,
                message: '对不起,超出投币上线了哦'
            })
            coin_who[id] = parseInt(coinCount) + parseInt(coin_who[id])
            coin_who = JSON.stringify(coin_who)
            coin_reduce()
        } catch (error) {
            coin_who = {
                [id]: coinCount
            }
            coin_who = JSON.stringify(coin_who)
            coin_reduce()
        }
    })
}

exports.subscribe = async (req, res) => {
    const { id, account } = req.body
    if (!id && !account) return
    let restult
    if (id) {
        restult = await new Promise(solve => {
            db.query('SELECT up from bilibili_videos where id=?', [id], (err, restult) => {
                if (err) return res.send({
                    status: 1,
                    message: err
                })
                solve(restult[0].up)
            })
        })
    } else {
        restult = account
    }
    db.query('SELECT id,fans from bilibili_personal where account=?', [restult], (err, myres) => {
        if (err) return res.send({
            status: 1,
            message: err
        })
        if (myres.length === 0) {
            return res.send({
                status: 1,
                message: '找不到这个人哦'
            })
        }
        db.query('SELECT idol from bilibili_personal where id=?', [req.user.id], (err, newres) => {
            let isFan = true
            let diolArr
            let fansArr
            if (newres[0].idol != null) {
                diolArr = newres[0].idol.split(',')
                if (diolArr.indexOf(String(myres[0].id)) != -1) {
                    isFan = false
                    diolArr.splice(diolArr.indexOf(String(myres[0].id)), 1)
                    if (diolArr.length === 0) {
                        diolArr = null
                        // console.log(diolArr);
                    } else {
                        diolArr = diolArr.toString()
                        // console.log(diolArr)
                    }
                } else {
                    if (myres[0].id == req.user.id) return res.send({
                        status: 1,
                        message: '自己不能关注自己哦'
                    })
                    diolArr.push(myres[0].id)
                    diolArr = diolArr.toString()
                }
            } else {
                if (myres[0].id == req.user.id) return res.send({
                    status: 1,
                    message: '自己不能关注自己哦'
                })
                diolArr = myres[0].id
            }

            if (myres[0].fans != null) {
                if (isFan) {
                    fansArr = myres[0].fans.split(',')
                    fansArr.push(req.user.id)
                    fansArr = fansArr.toString()
                } else {
                    fansArr = myres[0].fans.split(',')
                    fansArr.splice(fansArr.indexOf(String(req.user.id)), 1)

                    if (fansArr.length === 0) {
                        fansArr = null
                        // console.log(diolArr);
                    } else {
                        fansArr = fansArr.toString()
                        // console.log(diolArr)
                    }
                }
            } else {
                fansArr = req.user.id
            }
            db.query('UPDATE bilibili_personal SET idol=? where id=?', [diolArr, req.user.id], (err, idolres) => {
                if (err) return res.send({
                    status: 1,
                    message: err
                })
                if (idolres.affectedRows === 1) {
                    db.query('UPDATE bilibili_personal SET fans=? where id=?', [fansArr, myres[0].id], (err, fanres) => {
                        if (err) return res.send({
                            status: 1,
                            message: err
                        })
                        if (idolres.affectedRows === 1) {
                            res.send({
                                status: 0,
                                message: '操作成功'
                            })
                        }
                    })
                }
            })
        })
    })
}

exports.getfriends = async (req, res) => {
    let fansArr, idolArr, promiseListOne = [], promiseListTwo = [], newFans = [], newIdol = []
    db.query('SELECT idol,fans from bilibili_personal where id=?', [req.user.id], async (err, result) => {
        let idol = result[0].idol
        let fans = result[0].fans
        if (idol) {
            idolArr = idol.split(',')
            for (let i = 0; i < idolArr.length; i++) {
                promiseListOne.push(new Promise(resolve => {
                    db.query('SELECT username,profile,about,id,account from bilibili_personal where id=?', [idolArr[i]], (err, idolres) => {
                        if (err) return res.send({
                            status: 1,
                            message: err
                        })
                        newIdol.push(idolres[0])
                        resolve()
                    })
                })
                )
            }
        } else {
            idolArr = null
        }
        if (fans) {
            fansArr = fans.split(',')
            for (let i = 0; i < fansArr.length; i++) {
                promiseListTwo.push(new Promise(resolve => {
                    db.query('SELECT username,profile,about,id,account from bilibili_personal where id=?', [fansArr[i]], (err, fansres) => {
                        if (err) return res.send({
                            status: 1,
                            message: err
                        })
                        fansres[0].same = false
                        newFans.push(fansres[0])
                        resolve()
                    })
                })
                )
            }
        } else {
            fansArr = null
        }
        await Promise.allSettled(promiseListTwo)
        await Promise.allSettled(promiseListOne)
        if (idol && fans) {
            let SamePart = idolArr.filter(item => fansArr.includes(item))
            for (let i = 0; i < newFans.length; i++) {
                for (let x = 0; x < SamePart.length; x++) {
                    if (newFans[i].id == SamePart[x]) {
                        newFans[i].same = true
                    }
                }
            }
        }
        let friendList = {
            idol: newIdol,
            fans: newFans
        }
        res.send({
            status: 0,
            message: friendList
        })
    })
}

exports.get_someone_videos = (req, res) => {
    let up
    req.query.up ? up = req.query.up : up = req.user.username
    db.query('SELECT id from bilibili_videos where up=?', up, (err, result) => {
        if (err) return res.send({
            status: 1,
            message: err
        })
        if (result.length === 0) {
            return res.send({
                status: 1,
                message: '找不到这个人的id'
            })
        }
        if (result.length != 0) {
            return db.query('SELECT * from bilibili_videos where up=?', up, (err, videoRes) => {
                if (err) return res.send({
                    status: 1,
                    message: err
                })
                if (videoRes.length === 0) return res.send({
                    status: 1,
                    message: '没有查到视频哦'
                })
                res.send({
                    status: 0,
                    message: videoRes
                })
            })
        } else {
            return res.send({
                status: 1,
                message: '没有查到视频哦'
            })
        }
    })
}

exports.get_start = (req, res) => {
    let up
    req.query.up ? up = req.query.up : up = req.user.username
    db.query('SELECT star from bilibili_personal where account=?', up, async (err, result) => {
        if (err) return res.send({
            status: 1,
            message: err
        })
        let starList = []
        let starArray
        try {
            if (result[0].star) {
                starArray = result[0].star.split(',')
            } else {
                starArray = []
                starList = []
            }
        } catch (err) {
            return res.send({
                status: 1,
                message: '找不到这个人'
            })
        }
        let promiseList = []
        for (let i = 0; i < starArray.length; i++) {
            promiseList.push(new Promise((resolve) => {
                db.query('SELECT * from bilibili_videos where id=?', starArray[i], (err, video_res) => {
                    if (video_res.length != 0) {
                        starList.push(video_res[0])
                    }
                    resolve()
                })
            }))
        }
        await Promise.all(promiseList)
        res.send({
            status: 0,
            message: starList
        })
    })
}

exports.get_good_who = (req, res) => {
    let up
    req.query.up ? up = req.query.up : up = req.user.username
    db.query('SELECT good_who from bilibili_personal where account=?', up, async (err, result) => {
        if (err) return res.send({
            status: 1,
            message: err
        })
        let goodWhoList = []
        let goodWhoArray = []
        try {
            if (result[0].good_who) {
                goodWhoArray = result[0].good_who.split(',')
            } else {
                goodWhoArray = []
                goodWhoList = []
            } if (result[0].good_who) {
                goodWhoArray = result[0].good_who.split(',')
            } else {
                goodWhoArray = []
                goodWhoList = []
            }
        }
        catch (err) {
            return res.send({
                status: 1,
                message: '找不到这个人'
            })
        }
        let promiseList = []
        for (let i = 0; i < goodWhoArray.length; i++) {
            promiseList.push(new Promise((resolve) => {
                db.query('SELECT * from bilibili_videos where id=?', goodWhoArray[i], (err, video_res) => {
                    if (video_res.length != 0) {
                        goodWhoList.push(video_res[0])
                    }
                    resolve()
                })
            }))
        }
        await Promise.all(promiseList)
        res.send({
            status: 0,
            message: goodWhoList
        })
    })
}

exports.getIdolVideo = (res, req) => {
    db.query('SELECT idol from bilibili_personal where id=?', res.user.id, async (err, idol_res) => {
        if (err) return req.send({
            status: 1,
            message: err
        })
        let AllIdol, promiseList = [], AllVideo = []
        if (idol_res.length === 0) return req.send({
            status: 1,
            message: '您还没有关注任何up主'
        })
        if (idol_res[0].idol) {
            AllIdol = idol_res[0].idol.split(',')
            for (let i = 0; i < AllIdol.length; i++) {
                promiseList.push(new Promise(resolve => {
                    db.query('SELECT * from bilibili_videos where upid=?', AllIdol[i], async (err, video_res) => {
                        if (err) return req.send({
                            status: 1,
                            message: err
                        })
                        let goodPromise = []
                        for (let b = 0; b < video_res.length; b++) {
                            goodPromise.push(new Promise(resolve => {
                                db.query('SELECT good, star from bilibili_videos where id=?', video_res[b].id, (err, active_res) => {
                                    let good = active_res[0].good, star = active_res[0].star, goodArr, starArr
                                    good ? goodArr = good.split(',') : goodArr = []
                                    star ? starArr = star.split(',') : starArr = []
                                    goodArr.indexOf(String(res.user.id)) === -1 ? video_res[b].isGood = false : video_res[b].isGood = true
                                    starArr.indexOf(String(res.user.id)) === -1 ? video_res[b].isStar = false : video_res[b].isStar = true
                                    resolve()
                                })
                            }))
                        }
                        if (video_res.length != 0) {
                            db.query('SELECT username,profile from bilibili_personal where id=?', AllIdol[i], (err, up_res) => {
                                for (let a = 0; a < video_res.length; a++) {
                                    video_res[a].profile = up_res[0].profile
                                    video_res[a].username = up_res[0].username
                                }
                                db.query('SELECT id from bilibili_comment where video=?', [video_res[0].id], (err, commentres) => {
                                    for (let a = 0; a < video_res.length; a++) {
                                        video_res[a].commentCount = commentres.length
                                    }
                                    AllVideo.push(...video_res)
                                    resolve()
                                })
                            })
                        } else {
                            resolve()
                        }
                    })
                }))
            }
            await Promise.all(promiseList)
            AllVideo.sort(sortBy('time', -1))
            //attr：根据该属性排序；rev：升序1或降序-1，不填则默认为1
            function sortBy(attr, rev) {
                if (rev == undefined) { rev = 1 } else { (rev) ? 1 : -1; }
                return function (a, b) {
                    a = a[attr];
                    b = b[attr];
                    if (a < b) { return rev * -1 }
                    if (a > b) { return rev * 1 }
                    return 0;
                }
            }
            req.send({
                status: 0,
                message: AllVideo
            })
        } else {
            req.send({
                status: 1,
                message: '您还没有关注任何up主'
            })
        }
    })
}

exports.getComment = (req, res) => {
    const id = req.query.id
    db.query('SELECT * from bilibili_comment where video=?', id, async (err, comment_res) => {
        if (err) return res.send({
            status: 1,
            message: err
        })
        let promiseList = [], del = []
        for (let i = 0; i < comment_res.length; i++) {
            if (comment_res[i].good) {
                const commentArr = comment_res[i].good.split(',')
                comment_res[i].good = commentArr.length
                if (req.user) {
                    commentArr.indexOf(String(req.user.id)) == -1 ? comment_res[i].isGood = false : comment_res[i].isGood = true
                } else {
                    comment_res[i].isGood = false
                }
            } else {
                comment_res[i].good = 0
                comment_res[i].isGood = false
            }

            if (comment_res[i].disgood) {
                const commentArr = comment_res[i].disgood.split(',')
                comment_res[i].disgood = commentArr.length
                if (req.user) {
                    commentArr.indexOf(String(req.user.id)) == -1 ? comment_res[i].isDisgood = false : comment_res[i].isDisgood = true
                } else {
                    comment_res[i].isDisgood = false
                }
            } else {
                comment_res[i].disgood = 0
                comment_res[i].isDisgood = false
            }
            function getObjectByKey(array, key, value) {
                for (var i = 0; i < array.length; i++) {
                    if (array[i][key] === value) {
                        return array[i];
                    }
                }
                return null;
            }
            promiseList.push(new Promise(resolve => {
                db.query('SELECT profile,username,experience,account from bilibili_personal where id=?', comment_res[i].user_id, (err, user_res) => {
                    if (err) return res.send({
                        status: 1,
                        message: err
                    })
                    comment_res[i].username = user_res[0].username
                    comment_res[i].experience = user_res[0].experience
                    comment_res[i].profile = user_res[0].profile
                    comment_res[i].account = user_res[0].account
                    if (comment_res[i].call_who) {
                        db.query('SELECT username from bilibili_personal where id=?', comment_res[i].call_who, (err, call_res) => {
                            if (err) return res.send({
                                status: 1,
                                message: err
                            })
                            comment_res[i].call_name = call_res[0].username
                            resolve()
                        })
                    } else {
                        resolve()
                    }
                })
            }))
            await Promise.all(promiseList)
            if (comment_res[i].call) {
                if (getObjectByKey(comment_res, 'id', parseInt(comment_res[i].call))) {
                    getObjectByKey(comment_res, 'id', parseInt(comment_res[i].call)).sonComment ? 1 : getObjectByKey(comment_res, 'id', parseInt(comment_res[i].call)).sonComment = []
                    getObjectByKey(comment_res, 'id', parseInt(comment_res[i].call)).sonComment.push(comment_res[i])
                    del.push(i)
                }
            }
        }
        for (let i = del.length - 1; i >= 0; i--) {
            comment_res.splice(del[i], 1);
        }
        res.send({
            status: 0,
            message: comment_res
        })
    })
}
exports.sendComment = (req, res) => {
    const { videoId, commentId, comment, call_who, father } = req.body
    var reg = /[\t\r\f\n\s]*/g;
    if (comment.replace(reg, '') == '') return res.send({
        status: 1,
        message: '请输入评论'
    })
    db.query('insert into bilibili_comment (`video`,`comment`,`call`,`call_who`,`user_id`,`time`) values (?,?,?,?,?,?)', [videoId, comment, commentId, call_who, req.user.id, Date.now()], (err, comment_res) => {
        if (err) return res.send({
            status: 1,
            message: err.message
        })
        if (comment_res.affectedRows === 1) {
            db.query("SELECT  max(id) from bilibili_comment where user_id=?", req.user.id, (err, id_res) => {
                if (err) return res.send({
                    status: 1,
                    message: err
                })
                db.query('SELECT profile,username,experience from bilibili_personal where id=?', req.user.id, (err, user_res) => {
                    if (err) return res.send({
                        status: 1,
                        message: err.message
                    })
                    if (call_who) {
                        db.query('SELECT username,account from bilibili_personal where id=?', call_who, (err, call_res) => {
                            if (err) return res.send({
                                status: 1,
                                message: err.message
                            })
                            const data = {
                                id: id_res[0]['max(id)'],
                                videoId,
                                commentId,
                                comment,
                                call_who,
                                user_id: req.user.id,
                                profile: user_res[0].profile,
                                username: user_res[0].username,
                                experience: user_res[0].experience,
                                call_name: call_res[0].username,
                                account: req.user.username,
                                time: Date.now(),
                                good: 0
                            }
                            res.send({
                                status: 0,
                                message: '评论成功',
                                data
                            })
                        })
                    } else {
                        const data = {
                            id: id_res[0]['max(id)'],
                            videoId,
                            commentId,
                            comment,
                            call_who,
                            user_id: req.user.id,
                            profile: user_res[0].profile,
                            username: user_res[0].username,
                            experience: user_res[0].experience,
                            call_name: null,
                            account: req.user.username,
                            time: Date.now(),
                            good: 0
                        }
                        res.send({
                            status: 0,
                            message: '评论成功',
                            data
                        })
                    }
                })
            })

        }
    })
}

exports.goodComment = (req, res) => {
    const id = req.query.id
    if (!id) return
    db.query('select good,disgood from bilibili_comment where id=?', id, (err, good_res) => {
        if (good_res.length === 0) return
        let good = good_res[0].good
        let disgood = good_res[0].disgood
        if (good) {
            let goodArry = good.split(',')
            if (disgood) {
                let disgoodArry = disgood.split(',')
                if (disgoodArry.indexOf(String(req.user.id)) != -1) {
                    disgoodArry.splice(disgoodArry.indexOf(String(req.user.id)), 1);
                    disgood = disgoodArry.toString()
                }
            }
            if (goodArry.indexOf(String(req.user.id)) === -1) {
                goodArry.push(String(req.user.id))
                good = goodArry.toString()
            } else {
                goodArry.splice(goodArry.indexOf(String(req.user.id)), 1);
                good = goodArry.toString()
            }
        } else {
            good = String(req.user.id)
            if (disgood) {
                let disgoodArry = disgood.split(',')
                if (disgoodArry.indexOf(String(req.user.id)) != -1) {
                    disgoodArry.splice(disgoodArry.indexOf(String(req.user.id)), 1);
                    disgood = disgoodArry.toString()
                }
            }
        }
        db.query('UPDATE bilibili_comment SET good=?,disgood=? where id=?', [good, disgood, id], (err, restult) => {
            if (err) {
                res.send({
                    status: 0,
                    message: err
                })
            }
            if (restult.affectedRows === 1) {
                res.send({
                    status: 0,
                    message: '操作成功'
                })
            }
        })
    })
}


exports.disgoodComment = (req, res) => {
    const id = req.query.id
    if (!id) return
    db.query('select good,disgood from bilibili_comment where id=?', id, (err, good_res) => {
        let good = good_res[0].good
        let disgood = good_res[0].disgood
        if (disgood) {
            let disgoodArry = disgood.split(',')
            if (good) {
                let goodArry = good.split(',')
                if (goodArry.indexOf(String(req.user.id)) != -1) {
                    goodArry.splice(goodArry.indexOf(String(req.user.id)), 1);
                    good = goodArry.toString()
                }
            }
            if (disgoodArry.indexOf(String(req.user.id)) === -1) {
                disgoodArry.push(String(req.user.id))
                disgood = disgoodArry.toString()
            } else {
                disgoodArry.splice(disgoodArry.indexOf(String(req.user.id)), 1);
                disgood = disgoodArry.toString()
            }
        } else {
            disgood = String(req.user.id)
            if (good) {
                let goodArry = good.split(',')
                if (goodArry.indexOf(String(req.user.id)) != -1) {
                    goodArry.splice(goodArry.indexOf(String(req.user.id)), 1);
                    good = goodArry.toString()
                }
            }
        }
        db.query('UPDATE bilibili_comment SET good=?,disgood=? where id=?', [good, disgood, id], (err, restult) => {
            if (err) {
                res.send({
                    status: 1,
                    message: err
                })
            }
            if (restult.affectedRows === 1) {
                res.send({
                    status: 0,
                    message: '操作成功'
                })
            }
        })
    })
}


exports.addhistory = (req, res) => {
    let { id } = req.query
    db.query('select watch_history from bilibili_personal where id=?', req.user.id, (err, restult) => {
        if (err) return res.send({
            status: 1,
            message: err
        })
        let history = restult[0].watch_history
        if (history) {
            let historyArry = history.split(',')
            if (historyArry.indexOf(id) === -1) {
                historyArry.unshift(id)
                history = historyArry.toString()
            } else {
                historyArry.splice(historyArry.indexOf(String(id)), 1)
                historyArry.unshift(id)
                history = historyArry.toString()
            }
        } else {
            history = id
        }
        db.query('UPDATE bilibili_personal SET watch_history=? where id=?', [history, req.user.id], (err, update_restult) => {
            if (err) return res.send({
                status: 1,
                message: err
            })
            if (update_restult.affectedRows === 1) res.send({
                status: 0,
                message: '添加成功'
            })
        })
    })

}

exports.gethistory = (req, res) => {
    db.query('select watch_history from bilibili_personal where id=?', req.user.id, async (err, restult) => {
        let history = restult[0].watch_history
        let historyArry = history ? history.split(',') : []
        let promiseList = []
        let videos = []
        for (let i = 0; i < historyArry.length; i++) {
           await new Promise(resolve => {
                db.query('select title,id,time,up,upid,image from bilibili_videos where id=?', historyArry[i], (err, video_res) => {
                    if (err) resolve
                    db.query('select username from bilibili_personal where id=?', video_res[0].upid, (err, personal_res) => {
                        if (err) resolve
                        video_res[0].up = personal_res[0].username
                        resolve(videos.push(video_res[0]))
                    })
                })
            })
        }
        res.send({
            status: 0,
            message: videos
        })
    })
}